#include "login.h"
#include "ui_login.h"
#include <QMessageBox>
#include <QFile>
#include <QTextStream>
#include "register.h"
#include "chatwindow.h"
Login::Login(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::Login)
{
    ui->setupUi(this);

    connect(ui->pushButton_Login,&QPushButton::clicked,this,&Login::onLogin);
    connect(ui->pushButton_Register,&QPushButton::clicked,this,&Login::onRegiter);

    this->setWindowTitle("登录界面");
}

Login::~Login()
{
    delete ui;
}

void Login::onLogin()
{
    QString username = ui->lineEdit->text();
    QString password = ui->lineEdit_2->text();

    if(checkUser(username,password))
    {
        ChatWindow *chatWindow = new ChatWindow(this);
        chatWindow->show();
        this->hide();
    }
    else
    {
        QMessageBox::warning(this,"错误","用户名或密码错误");
    }

}

void Login::onRegiter()
{
    Register *registerWindow = new Register(this);
    registerWindow->show();
    this->hide();

}

bool Login::checkUser(QString username, QString password)
{
    QFile file("user.txt");
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        return false;
    }

    QTextStream in(&file);
    while (!in.atEnd())
    {
        //读取一行
        QString line = in.readLine();
        //分隔符
        QStringList parts = line.split(",");

        if (parts.size() == 2 && parts[0] == username && parts[1] == password)
        {
            file.close();
            return true;
        }
    }
    file.close();
    return false;
}


